﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hp.Vertica.Migration.SqlServer
{
    public class SchemaCollection
    {
        public Database Database { get; set; }

        private Dictionary<String, Schema> _schemasCache;

        public void Refresh()
        {
            Dictionary<String, Schema> current = new Dictionary<string, Schema>();
            using (SqlConnection conn = new SqlConnection(this.Database.DataSource.ConnectionString))
            {
                conn.Open();
                conn.ChangeDatabase(this.Database.Name);
                var cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT name FROM sys.schemas";
                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    String sname = dr.GetString(0);
                    String key = sname.ToUpper();
                    if (this._schemasCache != null && this._schemasCache.ContainsKey(key))
                    {
                        current.Add(key, this._schemasCache[key]);
                    }
                    else
                    {
                        current.Add(key, new Schema(sname, this.Database));
                    }
                }
            }
            this._schemasCache = current;
        }

        public List<Schema> Schemas
        {
            get
            {
                if (this._schemasCache == null)
                {
                    this.Refresh();
                }
                return this._schemasCache.Values.OrderBy(c => c.Name).ToList();
            }
        }

        public SchemaCollection(SqlServer.Database database)
        {
            // TODO: Complete member initialization
            this.Database = database;
        }

        public Schema this[String name]
        {
            get
            {
                if (this._schemasCache == null || !this._schemasCache.ContainsKey(name.ToUpper()))
                {
                    this.Refresh();
                }
                return this._schemasCache[name.ToUpper()];
            }
        }
    }
}
